#include "TextEditor.h"
#include "TextEditorMargine.h"

TextEditor::TextEditor(QWidget* parent):
    QPlainTextEdit(parent),
    _margine(new TextEditorMargine(this))
{
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
    highlightCurrentLine();
}

TextEditor::~TextEditor()
{

}

bool TextEditor::load(const QString& file)
{
    QFile f(file);
    if (f.open(QIODevice::ReadOnly)){
        setPlainText(f.readAll());
        path = path;
        emit contentLoaded();
        return true;
    }
    return false;
}

void TextEditor::resizeEvent(QResizeEvent *e)
{
    QPlainTextEdit::resizeEvent(e);
    QRect cr = contentsRect();
    _margine->setGeometry(QRect(cr.left(), cr.top(), _margine->lineNumberAreaWidth(), cr.height()));
}

void TextEditor::highlightCurrentLine()
{
    QList<QTextEdit::ExtraSelection> extraSelections;

    if (!isReadOnly()) {
        QTextEdit::ExtraSelection selection;

        QColor lineColor = QColor(18,18,18);

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extraSelections.append(selection);
    }

    setExtraSelections(extraSelections);
}


void TextEditor::del()
{
    textCursor().removeSelectedText();
}

void TextEditor::uppercase()
{
    QString text = textCursor().selectedText();
    textCursor().insertText(text.toUpper());
}

void TextEditor::lowercase()
{
    if (textCursor().hasSelection()){
        QString text = textCursor().selectedText();
        textCursor().insertText(text.toLower());
    }
}

void TextEditor::capitalize()
{
    if (textCursor().hasSelection()){
        QString text = textCursor().selectedText();
        text = text.left(1).toUpper()+text.right(text.length()-1).toLower();
        textCursor().insertText(text);
    }
}

bool TextEditor::reset()
{
    return false;
}

void TextEditor::jump(int line, int col)
{
}

void TextEditor::jumpOffset(int offset)
{

}
